<template>
    <a-modal v-bind="defaultModalProps" v-model:open="open" 
        :title="`${mapInterviewType.get(formState.interviewType)}邀请`"
        :width="540"
        :body-style="{paddingBlockStart:'34px',paddingBlockEnd: '54px'}"
        :ok-button-props="{loading}"
        @cancel="handleCancel"
        @ok="handleConfirm"
    >
        <div class="box-border">
            <a-flex :gap="12" align="center" class="mb-[30px]">
                <div class="text-secondary text-sm flex-none">面试类型</div>
                <a-radio-group v-model:value="formState.interviewType" style="padding-left: 18px;">
                    <a-space :size="40">
                        <a-radio v-for="item of interviewTypeOptions" :key="item.value" :value="item.value">
                            {{ item.label }}
                        </a-radio>
                    </a-space>
                </a-radio-group>
            </a-flex>
            <a-flex :gap="12" align="center" class="mb-5">
                <div class="text-secondary text-sm flex-none">招聘职位</div>
                <a-cascader placeholder="请选择招聘职位" size="large" style="width: 100%;" :options="cascadeJobTypes.options" v-model:value="formState.jobType" />
            </a-flex>
            <a-flex :gap="12" align="center" class="mb-5" v-if="formState.interviewType === EnumInterviewType.线下面试">
                <div class="text-secondary text-sm flex-none">面试地点</div>
                <a-select placeholder="请选择面试地点" size="large" style="width: 100%;" :options="interviewAddresses" v-model:value="formState.interviewAddress" :loading="interviewAddressLoading" />
            </a-flex>
            <a-flex :gap="12" align="center" class="mb-5" v-else>
                <div class="text-secondary text-sm flex-none">面试平台</div>
                <a-select placeholder="请选择面试平台" size="large" style="width: 100%;" :options="interviewPlatformOptions" v-model:value="formState.interviewPlatform" />
            </a-flex>
            <a-flex :gap="12" align="start" class="mb-5">
                <div class="text-secondary text-sm flex-none mt-2">备注事项</div>
                <a-textarea placeholder="请输入备注事项" size="large" style="width: 100%;" v-model:value="formState.note" :auto-size="{minRows:3}" :maxlength="140" show-count />
            </a-flex>
            <a-flex :gap="12" align="center" class="mb-5">
                <div class="text-secondary text-sm flex-none">面试时间</div>
                <a-flex :gap="10" align="center" :flex="1">
                    <DatePicker style="flex: 1;" size="large" v-model:value="formState.interviewDate" placeholder="请选择日期">
                        <template #suffixIcon>
                            <GpFontIcon name="icon-rili" class="text-primary" />
                        </template>
                    </DatePicker>
                    <span class="text-primary text-sm">~</span>
                    <TimePicker style="flex: 1;" size="large" v-model:value="formState.interviewTime" placeholder="请选择时间" format="HH:mm">
                        <template #suffixIcon>
                            <GpFontIcon name="icon-rili" class="text-primary" />
                        </template>
                    </TimePicker>
                </a-flex>
            </a-flex>
            <a-flex :gap="12" align="start" class="mb-5">
                <div class="text-secondary text-sm flex-none mt-2"><span class="invisible">影</span>联系人</div>
                <a-flex :gap="11" vertical>
                    <a-select placeholder="请选择联系人" size="large" style="width: 100%;" :options="interviewers" v-model:value="formState.interviewer" />
                    <p class="text-third text-xs !leading-4">
                        为保证求职者联系到面试企业，求职者接受面试后，可查看职位发布人和联系人的电话
                    </p>
                </a-flex>
            </a-flex>
        </div>
    </a-modal>
</template>
<script lang="ts" setup>
import { DatePicker, message, TimePicker } from 'ant-design-vue';
import { EnumInterviewType, type InterviewSendRequest } from '@/api/siderBar/model';
import { interviewPlatformOptions, interviewTypeOptions, mapInterviewType, type Exposed, type FormState, type Populate, type Props } from './types';
import { defaultModalProps } from '@/constants/comp-setting';
import { getJobGetjobaddresss } from '@/api/siderBar/job';
import { getSettingGetinterviewers } from '@/api/siderBar/setting';
import { postMychatSendinterviewChatId } from '@/api/siderBar/myChat';
import { useUserStore } from '@/stores';

defineOptions({
    name: "InviteInterviewModal",
    inheritAttrs: false
})
defineExpose<Exposed>({
    open(detail) {
        open.value = true
        populateDetail(toValue(detail))
    }
})
const emit = defineEmits<{
    success: [nextMessageId: number]
}>()
const { session } = defineProps<Props>()
const userStore = useUserStore()
const formState = ref(getInitialState())
const open = ref(false)
const loading = ref(false)
const { cascadeJobTypes, refreshAsync } = useFetchJobTypes()
const { data: _interviewAddresses, loading: interviewAddressLoading } = useRequest(getJobGetjobaddresss, {initialData: []})
const interviewAddresses = computed(() => {
    return _interviewAddresses.value!.map<IOption<number>>(l => ({label: [l.regionName, l.address].join(''), value: l.id}))
})
const { data: interviewers } = useRequest(getSettingGetinterviewers, {initialData: []})
function getInitialState(): FormState {
    return {
        interviewType: EnumInterviewType.线下面试
    }
}
function handleCancel() {
    open.value = false
    loading.value = false
    formState.value = getInitialState()
}
async function handleConfirm() {
    // validation & collection
    const params = validateAndCollect()
    if (!params) return
    // submition
    try {
        loading.value = true
        const nextMessageId = await postMychatSendinterviewChatId(session!, params)
        loading.value = false
        message.success('设置成功')
        emit("success", nextMessageId)
        handleCancel()
    } catch (error) {
        console.log(error)
        loading.value = false
    }
}
function validateAndCollect() {
    const state = formState.value
    const params = <InterviewSendRequest>{
        type: state.interviewType
    }
    if (!state.jobType || state.jobType.length <= 0) {
        message.error('请选择招聘职位')
        return false
    }
    const [,,jobTypeId] = state.jobType
    params.jobId = jobTypeId
    if (params.type === EnumInterviewType.线下面试) {
        if (!state.interviewAddress) {
            message.error('请选择面试地点')
            return false
        }
        params.jobAddressId = state.interviewAddress
    } else {
        if (!state.interviewPlatform) {
            message.error('请选择面试平台')
            return false
        }
        params.platform = state.interviewPlatform
    }
    if (state.note) params.note = state.note
    if (!state.interviewDate || !state.interviewTime) {
        message.error('请选择面试时间')
        return false
    }
    params.interviewTime = dateFormat(
        state.interviewDate.hour(state.interviewTime.hour()).minute(state.interviewTime.minute()),
        "long"
    )
    if (!state.interviewer) {
        message.error('请选择联系人')
        return false
    }
    params.interviewUserId = state.interviewer
    return params 
}
async function populateDetail(detail: Populate) {
    if (!detail) return
    if (isSetValue(detail.interviewType)) formState.value.interviewType = detail.interviewType
    if (isSetValue(detail.jobTypeId)) {
        await refreshAsync()
        nextTick(() => {
            const leaf = cascadeJobTypes.value.leafGroup.find(l => l.value === detail.jobTypeId)
            if (leaf) {
                const p = cascadeJobTypes.value.parentGroup.find(l => l.value === leaf.parentId)
                if (p) {
                    const r = cascadeJobTypes.value.rootGroup.find(l => l.value === p.parentId)
                    if (r) {
                        formState.value.jobType = [r.value, p.value, leaf.value]
                    }
                }
            }
        })
    }
    if (isSetValue(detail.interviewAddress)) formState.value.interviewAddress = detail.interviewAddress
    if (isSetValue(detail.note)) formState.value.note = detail.note
    if (isSetValue(detail.interviewDateTime)) {
        formState.value.interviewDate = dateUtil(detail.interviewDateTime)
        formState.value.interviewTime = dateUtil(detail.interviewDateTime)
    }
    const userId = detail.interviewer || userStore.userInfo?.id
    if (isSetValue(userId)) formState.value.interviewer = userId
}
</script>